package test;

import java.io.IOException;  
import java.net.InetSocketAddress;  
import java.nio.channels.SelectionKey;  
import java.nio.channels.Selector;  
import java.nio.channels.ServerSocketChannel;  
import java.util.Iterator;  
  
/** 
 * 服务器端 
 * @author Administrator 
 * 
 */  
public class Server {  
      
    public static String msg = "1";  
    public static boolean signal = false;  
    //超时时间  
    private static final int TimeOut = 3000;  
    //缓冲区大小  
    private static final int bufferSize = 1024;  
    //监听端口  
    private static final int Port = 10005;  
      
    public static void main(String[] args)throws IOException,InterruptedException{  
        //创建选择器  
        Selector selector = Selector.open();  
        //打开监听信道  
        ServerSocketChannel serverchannel = ServerSocketChannel.open();  
        //与本地端口绑定  
        serverchannel.socket().bind(new InetSocketAddress(Port));  
        //设置为非阻塞模式  
        serverchannel.configureBlocking(false);  
        //将选择器绑定到监听信道  
        serverchannel.register(selector, SelectionKey.OP_ACCEPT);  
        ProtocolImplement protocol = new ProtocolImplement(bufferSize);  
        System.out.println("服务器开启");  
        new ServerWriteThread();  
          
        while(true){  
            //等待某信道就绪或超时  
            if(selector.select(TimeOut) == 0){  
            	continue;  
            }  
            //取得迭代器，selectedkeys中包含了每个准备好I/O操作的信道的selectionkey  
            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();  
            while(keyIter.hasNext()){  
                SelectionKey key = keyIter.next();  
                try{  
                    if(key.isAcceptable()){  
                        protocol.handleAccept(key);  
                    }  
                    if(key.isReadable()){  
                        protocol.handleRead(key);  
                    }  
                    if(key.isValid() && key.isWritable()){  
                        if(signal == true){  
                            protocol.handleWrite(key);  
                        }  
                    }  
                }catch(IOException ex){  
                    keyIter.remove();  
                    continue;  
                }  
                //移除处理过的键  
                keyIter.remove();  
            }  
            signal = false;  
        }  
    }  
}  